package com.example.demo.Controller;

import com.example.demo.DAO.ShopDAO;
import com.example.demo.DAO.UserDAO;
import com.example.demo.DO.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserC {
    @Autowired
    UserDAO userDAO;

    @Autowired
    ShopDAO shopDAO;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model, HttpSession session, HttpServletResponse response){
        String user=request.getParameter("username");
        String password=request.getParameter("password");
        UserDO userDO=new UserDO();
        userDO.setUser(user);
        userDO.setPassword(password);
        session.setAttribute("username",user);
        if (userDAO.selectAll().contains(userDO)&&user!=null) {
            if (request.getParameter("1")!=null){
                Cookie cookie=new Cookie("username",user);
                cookie.setMaxAge(7*24*60*60);
                response.addCookie(cookie);
            }

            session.setAttribute("username",user);
            model.addAttribute("name", user);
            model.addAttribute("shop_list",shopDAO.selectAll());
            if (user.equals("李文博")){
                return "manage_shop";
            }
            return "Shop";
        }
        if (user!=null){
            model.addAttribute("error","用户名或密码错误");
        }
        return "Login";
    }

    @RequestMapping("/sign")
    public String sign(HttpServletRequest request ,Model model){
        String user1=request.getParameter("username1");
        String password1=request.getParameter("password1");
        String password2=request.getParameter("password2");
        if (user1!=null&&userDAO.selectId(user1).size()==0&&password1.equals(password2)){
            userDAO.insert(user1,password1);
            return "Login";
        }
        if (user1!=null){
            model.addAttribute("error","用户名已存在或密码不重复");
        }
        return "Sign";
    }
}